﻿using System;
using System.Collections;
using System.Web;


namespace App.Code
{
    public class Cache : ICache
    {
        private static System.Web.Caching.Cache cache = HttpRuntime.Cache;

        /// <summary>
        /// 通过键值获取cookie得到实体
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="cacheKey">键值</param>
        /// <returns></returns>
        public T GetCache<T>(string cacheKey) where T : class
        {
            if (cache[cacheKey] != null)
            {
                return (T)cache[cacheKey];
            }
            return default(T);
        }

        /// <summary>
        /// 写入cookie
        /// </summary>
        /// <param name="value">要写入的对象</param>
        /// <param name="cacheKey">缓存key</param>
        public void WriteCache<T>(T value, string cacheKey) where T : class
        {
            cache.Insert(cacheKey, value, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        /// <summary>
        /// 写入cookie
        /// </summary>
        /// <param name="value">要写入的对象</param>
        /// <param name="cacheKey">缓存key</param>
        /// <param name="expireTime">过期时间</param>
        public void WriteCache<T>(T value, string cacheKey, DateTime expireTime) where T : class
        {
            cache.Insert(cacheKey, value, null, expireTime, System.Web.Caching.Cache.NoSlidingExpiration);
        }

        /// <summary>
        /// 删除cookie
        /// </summary>
        /// <param name="cacheKey">缓存key</param>
        public void RemoveCache(string cacheKey)
        {
            cache.Remove(cacheKey);
        }

        /// <summary>
        /// 删除所有缓存
        /// </summary>
        public void RemoveCache()
        {
            IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                cache.Remove(CacheEnum.Key.ToString());
            }
        }
    }
}
